#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "ff.h"
#include "diskio.h"

void fopen_test(void)
{
    char data[FF_MAX_SS];
    memset(data, 0xFF, FF_MAX_SS);
    int read_rslt;

    FILE *fp = fopen("test.img", "r+");
    if(NULL == fp) {
        printf("open failed\r\n");
    }


    fseek(fp, 2048, SEEK_SET);

    read_rslt = fwrite(data, FF_MAX_SS, 1, fp);

    printf("write: %d\r\n", read_rslt);

    fseek(fp, 0, SEEK_SET);
    // read_rslt = fread(data, FF_MAX_SS, 1, fp);
    read_rslt = fwrite(data, FF_MAX_SS, 1, fp);

    printf("write: %d\r\n", read_rslt);

    memset(data, 0x00, FF_MAX_SS);

    fseek(fp, 0, SEEK_SET);
    read_rslt = fread(data, FF_MAX_SS, 1, fp);
    printf("read_rslt: %d\r\n", read_rslt);

    // fclose(fp);

}

void fatfs_test(void)
{
    FATFS fs;           /* Filesystem object */
    FIL fil;            /* File object */
    FRESULT res;        /* API result code */
    UINT bw;            /* Bytes written */
    BYTE work[FF_MAX_SS]; /* Work area (larger is better for processing time) */

    unsigned char rdata[32];

    MKFS_PARM opt = {
        FM_FAT32,
        0,
        0,
        0,
        0
    };


    // f_mount(&fs, "0:", 1);

    res = f_mkfs("0:", 0, work, sizeof(work));
    // // or
    // res = f_mkfs("0:", &opt, work, sizeof(work));
    
    printf("mkfs res %d\r\n", res);

    if(res != FR_OK) {
        return;
    }

    f_mount(&fs, "0:", 1);

    res = f_open(&fil, "hello.txt", FA_CREATE_NEW | FA_WRITE);

    printf("open res %d\r\n", res);

    if(res != FR_OK) {
        return;
    }

    f_write(&fil, "Hello, World!\r\n", 15, &bw);

    if (bw != 15) {
        printf("write failed: %d\r\n", bw);
    }

    f_close(&fil);

    res = f_open(&fil, "hello.txt", FA_READ);

    printf("reopen res %d\r\n", res);

    if(res != FR_OK) {
        return;
    }

    memset(rdata, 0xFF, 32);

    res = f_read(&fil, rdata, 15, &bw);

    printf("the bw is %d\r\n", bw);

    printf("rdata: %s\n", rdata);

    f_close(&fil);
}

int main(int argv, char *args[])
{
    printf("This is fastfs pc test pro\r\n");
    fatfs_test();
    // fopen_test();
    return 0;
}